package com.li.utils;

import com.alibaba.fastjson.JSON;
import com.li.Constants;
import com.li.entity.AllWeatherInfo;
import com.li.entity.BaseWeatherInfo;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class SubscriptionMessageUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(SubscriptionMessageUtil.class);

    // 测试号appId
    private static final String APP_ID = "";
    // 测试号appSecret
    private static final String SECRET_ID = "";
    // 模板ID
    private static final String TEMPLATE_ID = "";
    // 接收人
    private static final String TO_USER = "";
    // 高德地图API  天气key
    private static final String WEATHER_KEY = "";
    // 城市 上海
    private static final String WEATHER_CITY = "310112";

    public static void sendOrderMsg() {
        LOGGER.info("SubscriptionMessageUtil start...");

        // 天数
        LocalDate startDate = LocalDate.of(2019, 3, 16);
        LocalDate nowDate = LocalDate.now();
        long days = nowDate.toEpochDay() - startDate.toEpochDay();

        // 天气
        AllWeatherInfo.Forecast forecast = getAllWeatherInfo();
        AllWeatherInfo.Forecast.Cast cast = forecast.getCasts().get(0);

        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId(APP_ID);
        wxStorage.setSecret(SECRET_ID);

        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);

        // 此处的 key/value 需和模板消息对应
        List<WxMpTemplateData> wxMpTemplateDataList = Arrays.asList(
                new WxMpTemplateData("name", "li", "#FF6EC7"),
                new WxMpTemplateData("days", String.valueOf(days), "#FF0000"),
                new WxMpTemplateData("date", cast.getDate()),
                new WxMpTemplateData("week", cast.getWeek()),
                new WxMpTemplateData("city", forecast.getProvince() + forecast.getCity()),
                new WxMpTemplateData("dayweather", cast.getDayweather()),
                new WxMpTemplateData("nightweather", cast.getNightweather()),
                new WxMpTemplateData("daytemp", cast.getDaytemp()),
                new WxMpTemplateData("nighttemp", cast.getNighttemp()),
                new WxMpTemplateData("winddirection", cast.getDaywind()),
                new WxMpTemplateData("windpower", cast.getDaypower()),
                new WxMpTemplateData("reporttime", forecast.getReporttime())
        );

        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(TO_USER)
                .templateId(TEMPLATE_ID)
                .data(wxMpTemplateDataList)
                .build();

        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (Exception e) {
            System.out.println("推送失败：" + e.getMessage());
        }
    }

    /**
     * 实时天气
     * @return
     */
    private static BaseWeatherInfo getWeatherInfo() {
        String response = OkHttpUtils.builder().url("https://restapi.amap.com/v3/weather/weatherInfo")
                .addParam("key", WEATHER_KEY)
                .addParam("city", WEATHER_CITY)
                .addParam("extensions", "base")
                .get().sync();
        LOGGER.info("=========>SubscriptionMessageUtil_getWeatherInfo_response: {}", response);
        return JSON.parseObject(response, BaseWeatherInfo.class);
    }

    /**
     * 天气
     * @return
     */
    private static AllWeatherInfo.Forecast getAllWeatherInfo() {
        String response = OkHttpUtils.builder().url("https://restapi.amap.com/v3/weather/weatherInfo")
                .addParam("key", WEATHER_KEY)
                .addParam("city", WEATHER_CITY)
                .addParam("extensions", "all")
                .get().sync();
        LOGGER.info("=========>SubscriptionMessageUtil_getWeatherInfo_response: {}", response);

        AllWeatherInfo allWeatherInfo = JSON.parseObject(response, AllWeatherInfo.class);

        if (Objects.nonNull(allWeatherInfo) && Constants.Flag.YES.equals(allWeatherInfo.getStatus())) {
            List<AllWeatherInfo.Forecast> forecasts = allWeatherInfo.getForecasts();
            if (!CollectionUtils.isEmpty(forecasts)) {
                return forecasts.get(0);
            }
        }
        return null;
    }
}

